* create fertility record
global data_folder "W:\intimate\data"
global log_folder "W:\intimate\dofiles\logs"
global result_folder "W:\intimate\results"


import sas using "D:\c55\custom-made\u1067_al3\u1067_al3_vanhempi_lapsi.sas7bdat", clear
count if isa_aiti==""

*keep biological parent and children 
keep if (isa_aiti=="1" | isa_aiti=="2")

gen byc=substr(syntykk_lapsi, 1,4)
tab byc
destring byc, replace 

sort shnro_v byc

bysort shnro_v: gen child_id=_n

* reshape in wide format
keep byc shnro_v child_id 
reshape wide byc, i(shnro_v) j(child_id)
 
 * complete fertility over the lifecycle
 gen tot_children=0
forvalues i=1(1)24{
	replace tot_children=tot_children+(byc`i'!=.)
}


rename shnro_v shnro


* construct number of children in each year 
forvalues y=2001(1)2019{
	gen nchild=0
	gen byc_yst=.
	forvalues i=1(1)24{
	replace nchild=nchild+1 if byc`i'<=`y' & byc`i'!=. 
	replace byc_yst=byc`i' if nchild==`i'
}

preserve
keep shnro nchild byc_yst
save  "$data_folder\fertility_`y'.dta", replace 
restore 
drop nchild byc_yst
}



clear
forvalues y=2001/2019{
	use "$data_folder\fertility_`y'.dta", clear
	gen year=`y'
	
	gen age_yst=year-byc_yst
	gen year_event=year

	save "$data_folder\fertility_`y'.dta", replace 

}




clear
forvalues y=2001/2019{
	append using "$data_folder\fertility_`y'.dta"
}


save "$data_folder\fertility_allyears.dta", replace 

